package com.ctz.commonframe.ui;


import java.io.File;
import java.util.List;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;

import com.ctz.commonframe.entity.ImageItem;
import com.ctz.commonframe.utils.Logger;
import com.ctz.commonframe.utils.PickImageUtil;
//import com.tencent.smtt.sdk.DownloadListener;
//import com.tencent.smtt.sdk.ValueCallback;
//import com.tencent.smtt.sdk.WebChromeClient;
//import com.tencent.smtt.sdk.WebSettings;
//import com.tencent.smtt.sdk.WebView;
//import com.tencent.smtt.sdk.WebViewClient;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.GeolocationPermissions;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ProgressBar;

@SuppressLint("NewApi")
public class WebViewActivity extends TitleBarActivity {
	public final static String EXTRA_KEY_URL = "url";
	public final static String EXTRA_KEY_TITLE = "title";
	public final static String EXTRA_KEY_TITLE_RIGHT_TEXT = "title_right_text";
	public final static String EXTRA_KEY_TITLE_RIGHT_RES = "title_right_res";
	public final static String EXTRA_KEY_TITLE_RIGHT_CLICK_TO_CLASS = "title_right_click_to_class";
	public final static String EXTRA_KEY_RELOGIN = "relogin";
	public final static String EXTRA_KEY_QRCODE_CALLBACK_FUNCTION_NAME = "qrcode_result_callback_function_name";
	public final static String EXTRA_KEY_QRCODE_RESULT = "qrcode_result";
	public final static int REQUEST_CODE_QRCODE_SCAN = 3001;


	public WebView webView;
    private BottomMenuDialog addImageDialog;
    protected ProgressBar progressBar;
	protected String mTitle = "";
	protected String mTitleRightText = "";
	protected int mTitleRightRes = 0;
	protected String mTitleRightClickToClass = "";
	protected String mUrl = "";
	private ImageItem imageItem;

	private static WebViewActivity instance;

	public static WebViewActivity getInstance() {
	    return instance;
    }

	@SuppressLint("SetJavaScriptEnabled")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		FrameLayout parent = new FrameLayout(this);
		parent.setBackgroundColor(Color.WHITE);
		parent.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
		webView = new WebView(this);
		parent.addView(webView, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
		progressBar = new ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal);
		progressBar.setMax(100);
        parent.addView(progressBar, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, 10));
		setContentView(parent);
		Intent intent = getIntent();
		mTitle = intent.getStringExtra(EXTRA_KEY_TITLE);
		mTitleRightText = intent.getStringExtra(EXTRA_KEY_TITLE_RIGHT_TEXT);
		mTitleRightRes = intent.getIntExtra(EXTRA_KEY_TITLE_RIGHT_RES, 0);
		mTitleRightClickToClass = intent.getStringExtra(EXTRA_KEY_TITLE_RIGHT_CLICK_TO_CLASS);
		mUrl = intent.getStringExtra(EXTRA_KEY_URL);
		if(TextUtils.isEmpty(mTitle) && TextUtils.isEmpty(mTitleRightText) && mTitleRightRes == 0){
			setTitleEnable(false);
		}
		if(!TextUtils.isEmpty(mTitle)){
			setTitleMiddleText(mTitle);
		}
		if(!TextUtils.isEmpty(mTitleRightText)){
			setTitleRightText(mTitleRightText);
		}
		if(mTitleRightRes > 0){
			setTitleRightRes(mTitleRightRes);
		}
		if(!TextUtils.isEmpty(mTitleRightClickToClass)){
			setTitleRightClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					Intent intent = new Intent();
					intent.setClassName(WebViewActivity.this, mTitleRightClickToClass);
					startActivity(intent);
				}
			});
		}
		
		webView.setWebViewClient(new MyWebViewClient());
		WebSettings webSettings = webView.getSettings();
        webSettings.setLoadsImagesAutomatically(true);
        webSettings.setAllowContentAccess(true);
		webSettings.setAllowFileAccess(true);
        webSettings.setAllowFileAccessFromFileURLs(true);
        webSettings.setAllowUniversalAccessFromFileURLs(true);
		webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
//		webSettings.setSupportZoom(true);
//		webSettings.setBuiltInZoomControls(true);
		webSettings.setUseWideViewPort(true);
		webSettings.setSupportMultipleWindows(true);
		webSettings.setLoadWithOverviewMode(true);
		webSettings.setAppCacheEnabled(true);
		webSettings.setDatabaseEnabled(true);
		webSettings.setDomStorageEnabled(true);
        //noinspection deprecation
        webSettings.setJavaScriptEnabled(true);
		webSettings.setGeolocationEnabled(true);
		webSettings.setAppCacheMaxSize(Long.MAX_VALUE);
		webSettings.setAppCachePath(this.getDir("appcache", Context.MODE_PRIVATE).getPath());
		webSettings.setDatabasePath(this.getDir("databases", Context.MODE_PRIVATE).getPath());
		webSettings.setGeolocationDatabasePath(this.getDir("geolocation", Context.MODE_PRIVATE).getPath());
		webSettings.setSavePassword(true);
		webSettings.setSaveFormData(true);// 保存表单数据
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
//        }
		// webSettings.setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);
        //noinspection deprecation
        webSettings.setPluginState(WebSettings.PluginState.ON);
		// webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);
		// webSettings.setPreFectch(true);
        webView.addJavascriptInterface(new JSFunction(), "android");
		webView.setWebChromeClient(new MyWebChromeClient());
		webView.setDownloadListener(new MyWebViewDownLoadListener());
		webView.loadUrl(mUrl);
//        webView.loadDataWithBaseURL(null, mUrl, "text/html", "utf-8", null);
//		CookieSyncManager.createInstance(this);
//		CookieSyncManager.getInstance().sync();
        instance = this;
	}



	@Override
	protected void onDestroy() {
		if (webView != null)
			webView.destroy();
        instance = null;
		super.onDestroy();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (event.getAction() == KeyEvent.ACTION_DOWN) {
            switch (keyCode) {
                case KeyEvent.KEYCODE_BACK:
                    if (webView != null && webView.canGoBack()) {
                        webView.goBack();
                    } else {
                        finish();
                    }
                    return true;
            }
		}
		return super.onKeyDown(keyCode, event);
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent intent){
	    switch (requestCode) {
            case PickImageUtil.REQUEST_CODE_TAKE_PHOTO:
            case PickImageUtil.REQUEST_CODE_SELECT_IMAGE:
            case PickImageUtil.REQUEST_CODE_PICK_FILE:
                PickImageUtil.getInstance().handleActivityResult(requestCode, resultCode, intent);
                break;
            case REQUEST_CODE_QRCODE_SCAN:
                if (intent != null) {
                   String result = intent.getStringExtra(EXTRA_KEY_QRCODE_RESULT);
                   if (!TextUtils.isEmpty(result)) {
                       webView.loadUrl("javascript:" + result);
                   }
                }

                break;
            default:
                break;
        }
	}
	
	private class MyWebViewDownLoadListener implements DownloadListener {
		  
        @Override  
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype,  
                                    long contentLength) {  
            Uri uri = Uri.parse(url);  
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);  
            startActivity(intent);  
        }  
    } 

	private class MyWebViewClient extends WebViewClient {
	    @Override
	    public boolean shouldOverrideUrlLoading(WebView view, String url) {
	        Logger.e("WebView current url:" + url);
	        if (view.canGoBack())
	            return true;
	        if (url.contains("blanck")) {
	            return true;
            }
	    	if (url.startsWith("http:") || url.startsWith("https:")) {
                if (url.equals("http:") || url.contains("LoginOut") || url.contains("close") || url.contains("closeWindow=true")) {
                    finish();
                } else {
                    view.loadUrl(url);
                }
                return true;
            }
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            startActivity( intent );
            return true;
        }


        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
	        Logger.e("onPageStarted url:" + url);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            Logger.e("onPageFinished url:" + url);
        }
    }
	
	private class MyWebChromeClient extends WebChromeClient {

	    @Override
        public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
            callback.invoke(origin, true, true);
            super.onGeolocationPermissionsShowPrompt(origin, callback);
        }

        @Override
        public void onProgressChanged(WebView webView, int newProgress) {
            progressBar.setProgress(newProgress);
            if (progressBar != null && newProgress != 100) {
                progressBar.setVisibility(View.VISIBLE);
            } else if (progressBar != null) {
                progressBar.setVisibility(View.GONE);
            }
        }

        private void handleChooserFileResult(List<ImageItem> imageList, ValueCallback<Uri> uploadMsg){
            if (imageList != null && imageList.size() > 0 && imageList.get(0).imagePath != null){
                String path = imageList.get(0).imagePath;
                Uri uri = Uri.fromFile(new File(path));
                Logger.e("上传文件path:" + path + ", uri:" + uri);
                uploadMsg.onReceiveValue(uri);
            } else {
                uploadMsg.onReceiveValue(null);
            }
        }

        private void handleChooserFileResult5(ValueCallback<Uri[]> filePathCallback){
            if (imageItem != null && imageItem.imagePath != null){
                Uri uri = Uri.fromFile(new File(imageItem.imagePath));
                Logger.e("webview image path", imageItem.imagePath);
                filePathCallback.onReceiveValue(new Uri[]{uri});
            } else {
                filePathCallback.onReceiveValue(null);
            }
        }

        // Android 4.1.1+
        public void openFileChooser(final ValueCallback<Uri> uploadMsg, String acceptType, String capture){
            Logger.e("WebView openFileChooser");
            if (!TextUtils.isEmpty(capture)) {
                PickImageUtil.getInstance().takePhoto(WebViewActivity.this, new PickImageUtil.OnPickImageResultListener() {
                    @Override
                    public void onResult(List<ImageItem> imageList) {
                        handleChooserFileResult(imageList, uploadMsg);
                    }
                });
            } else {
                if ("image/*".equals(acceptType)) {
                    PickImageUtil.getInstance().selectImage(WebViewActivity.this, new PickImageUtil.OnPickImageResultListener() {
                        @Override
                        public void onResult(List<ImageItem> imageList) {
                            handleChooserFileResult(imageList, uploadMsg);
                        }
                    });
                } else {
                    PickImageUtil.getInstance().pickFile(WebViewActivity.this, new PickImageUtil.OnPickImageResultListener() {
                        @Override
                        public void onResult(List<ImageItem> imageList) {
                            handleChooserFileResult(imageList, uploadMsg);
                        }
                    });
                }
            }
	    }
	    
	    // Android 5.0+
	    @SuppressLint("NewApi")
		public boolean onShowFileChooser(WebView mWebView, final ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams){
            Logger.e("WebView onShowFileChooser");
//            if (fileChooserParams.isCaptureEnabled()) {
//                PickImageUtil.getInstance().takePhoto(WebViewActivity.this, new PickImageUtil.OnPickImageResultListener() {
//                    @Override
//                    public void onResult(List<ImageItem> imageList) {
//                        handleChooserFileResult5(imageList, filePathCallback);
//                    }
//                });
//            }else{
//                String[] types = fileChooserParams.getAcceptTypes();
//                boolean isPickImage = false;
//                for (String s: types){
//                    if (s.startsWith("image/")) {
//                        isPickImage = true;
//                    }
//                }
//                if (isPickImage) {
//                    PickImageUtil.getInstance().selectImage(WebViewActivity.this, new PickImageUtil.OnPickImageResultListener() {
//                        @Override
//                        public void onResult(List<ImageItem> imageList) {
//                            handleChooserFileResult5(imageList, filePathCallback);
//                        }
//                    });
//                } else {
//                    PickImageUtil.getInstance().pickFile(WebViewActivity.this, new PickImageUtil.OnPickImageResultListener() {
//                        @Override
//                        public void onResult(List<ImageItem> imageList) {
//                            handleChooserFileResult5(imageList, filePathCallback);
//                        }
//                    });
//                }
//            }

            String[] types = fileChooserParams.getAcceptTypes();
            boolean isPickImage = false;
            for (String s: types){
                Logger.e("acceptType", s);
                if (s.startsWith("image/")) {
                    isPickImage = true;
                }
            }
            if (isPickImage) {
                showAddImageDialog(filePathCallback);
            }
	        return true;
	    }

        private void showAddImageDialog(final ValueCallback<Uri[]> filePathCallback) {
            if (addImageDialog == null)
                addImageDialog = new BottomMenuDialog(WebViewActivity.this, BottomMenuDialog.TYPE_IMAGE_CAPTURE);

            addImageDialog.setOnMenu1ClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        PickImageUtil.getInstance().selectImage(WebViewActivity.this, new PickImageUtil.OnPickImageResultListener() {
                            @Override
                            public void onResult(List<ImageItem> imageList) {
                                imageItem = imageList.get(0);
                                handleChooserFileResult5(filePathCallback);
                            }
                        });
                        addImageDialog.dismiss();
                    }
            });
            addImageDialog.setOnMenu2ClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        PickImageUtil.getInstance().takePhoto(WebViewActivity.this, new PickImageUtil.OnPickImageResultListener() {
                            @Override
                            public void onResult(List<ImageItem> imageList) {
                                imageItem = imageList.get(0);
                                handleChooserFileResult5(filePathCallback);
                            }
                        });
                        addImageDialog.dismiss();
                    }
            });

            addImageDialog.show();
        }

//		@Override
//		public boolean onJsConfirm(WebView arg0, String arg1, String arg2,
//								   JsResult arg3) {
//			return super.onJsConfirm(arg0, arg1, arg2, arg3);
//		}
//
//		View myVideoView;
//		View myNormalView;
//		IX5WebChromeClient.CustomViewCallback callback;
//
//		// /////////////////////////////////////////////////////////
//		//
//		/**
//		 * 全屏播放配置
//		 */
//		@Override
//		public void onShowCustomView(View view, IX5WebChromeClient.CustomViewCallback customViewCallback) {
//			FrameLayout normalView = (FrameLayout) findViewById(R.id.web_filechooser);
//			ViewGroup viewGroup = (ViewGroup) normalView.getParent();
//			viewGroup.removeView(normalView);
//			viewGroup.addView(view);
//			myVideoView = view;
//			myNormalView = normalView;
//			callback = customViewCallback;
//		}
//
//		@Override
//		public void onHideCustomView() {
//			if (callback != null) {
//				callback.onCustomViewHidden();
//				callback = null;
//			}
//			if (myVideoView != null) {
//				ViewGroup viewGroup = (ViewGroup) myVideoView.getParent();
//				viewGroup.removeView(myVideoView);
//				viewGroup.addView(myNormalView);
//			}
//		}
//
//		@Override
//		public boolean onJsAlert(WebView arg0, String arg1, String arg2,
//								 JsResult arg3) {
//			/**
//			 * 这里写入你自定义的window alert
//			 */
//			return super.onJsAlert(null, arg1, arg2, arg3);
//		}
	}

	private class JSFunction extends Object {
	    @JavascriptInterface
	    public void directive(String code) {
	        Logger.e("directive:", "JS function:" + code);
	        if ("closeWindow".equals(code)) {
                WebViewActivity.this.finish();
            } else if("relogin".equals(code)) {
                if (onWebViewEventListener != null) {
                    onWebViewEventListener.onRelogin();
                }
            }
        }

        @JavascriptInterface
        public void qr(String callbackFunctionName) {
            startActivityForResult(new Intent(WebViewActivity.this, QRCodeScanActivity.class).putExtra(EXTRA_KEY_QRCODE_CALLBACK_FUNCTION_NAME, callbackFunctionName), REQUEST_CODE_QRCODE_SCAN);
        }

        @JavascriptInterface
        public void getLocation (String callbackFunctionName) {
            if (onWebViewEventListener != null) {
                onWebViewEventListener.onStartLocation(webView, callbackFunctionName);
            }
        }

        @JavascriptInterface
        public void getUnread(String appId, String callbackFunctionName) {
	        Logger.e("getUnread");
	        if (onWebViewEventListener != null) {
	            onWebViewEventListener.onGetUnread(webView, appId, callbackFunctionName);
            }
        }

        @JavascriptInterface
        public void setRead(String appId, String code) {
	        if (onWebViewEventListener != null) {
	            onWebViewEventListener.onSetRead(appId, code);
            }
        }


    }

    public interface OnWebViewEventListener {
	    void onRelogin();
	    void onStartLocation(WebView webView, String callbackFunctionName);
	    void onGetUnread(WebView webView, String appId, String callbackFunctionName);
	    void onSetRead(String appId, String code);
    }

    private static OnWebViewEventListener onWebViewEventListener;
    public static void setOnWebViewEventListener (OnWebViewEventListener listener) {
	    onWebViewEventListener = listener;
    }
}
